/**
 * color 输入色值,hex rgb rgba
 * opacity 输入透明度
 * 返回结果:透明度为 opacity 的 rgba 色值
 */
export function setColorOpacity(color, opacity) {
  let c = color
  // to varify color format
  var regHex = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/
  var regRGB = /^rgb\(([0-9]|[0-9][0-9]|25[0-5]|2[0-4][0-9]|[0-1][0-9][0-9])\,([0-9]|[0-9][0-9]|25[0-5]|2[0-4][0-9]|[0-1][0-9][0-9])\,([0-9]|[0-9][0-9]|25[0-5]|2[0-4][0-9]|[0-1][0-9][0-9])\)$/i
  var regRGBA = /^rgba\(([0-9]|[0-9][0-9]|25[0-5]|2[0-4][0-9]|[0-1][0-9][0-9])\,([0-9]|[0-9][0-9]|25[0-5]|2[0-4][0-9]|[0-1][0-9][0-9])\,([0-9]|[0-9][0-9]|25[0-5]|2[0-4][0-9]|[0-1][0-9][0-9])\,(1|1.0|0.[0-9])\)$/i

  // if hex，transform to rgb
  if (regHex.test(c)) {
    c = c.length === 4 ? c + c.slice(1, 4) : c // #000 格式补全6位
    const red = parseInt('0x' + c.slice(1, 3))
    const green = parseInt('0x' + c.slice(3, 5))
    const yellow = parseInt('0x' + c.slice(5, 7))
    c = `rgb(${red},${green},${yellow})`
  }

  // if rgb，transform to  rgba
  if (regRGB.test(c)) {
    const rgb = c.match(regRGB)
    c = `rgba(${rgb[1]},${rgb[2]},${rgb[3]},1)`
  }

  // if rgba , return color with opacity
  if (regRGBA.test(c)) {
    const rgba = c.match(regRGBA)
    if (opacity || opacity === 0) {
      return `rgba(${rgba[1]},${rgba[2]},${rgba[3]},${opacity})`
    } else {
      return c
    }
  } else {
    return 'wrong color value'
  }
}
